String.prototype.htmlXss = function() {
    var s = this;
    if (s.length == 0) return "";
    s = s.replace(/&/g, "&amp;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    s = s.replace(/ /g, "&nbsp;");
    s = s.replace(/\'/g, "&#39;");
    s = s.replace(/\"/g, "&quot;");
    return s;
}

JitianIm = {
    //初始化加载消息数量
    initMsgNum: __DEBUG ? 20 : 800,
    //后台链接
    adminUrl: __HTTP + '://' + __HOST + '/admin/',
    //请求接口
    baseUrl: __HTTP + '://' + __HOST + ':9501/',
    //websocket接口
    websocketUrl: 'ws://' + __HOST + ':9502/',

    //聊天用户列表
    userList: [],

    //管理的账号ID
    validUserIds: [],

    curListKey: '',
    curUserId: 0,
    curUserName: '',
    curUserAccount: '',
    curChatId: 0,
    curChatName: '',
    curChatAccount: '',
    curMomentId: 0,

    webSocket: null,

    //文字消息
    msgTextType: 1,
    //图片消息
    msgImageType: 2,

    //最大显示消息数
    msgMaxNum: 100,

    //初始化数据
    init: function() {
        this.initUserList();
        this.initWebsocket();
    },

    //初始化用户列表
    initUserList: function(newTipKey) {
        var initUserUrl = this.baseUrl + 'message/im/official_users',
            self = this;
        //alert(initUserUrl);
        this.postReq(initUserUrl, { msg_num: this.initMsgNum, admin_id: __ADMINID }, function(response) {
            self.userList = response.data.list;
            self.validUserIds = response.data.validUserIds;
            console.log(self.userList);
            console.log('管理有效账号：', self.validUserIds)
            self.buildUserList();
            if (newTipKey != undefined) self.showNewTip(newTipKey);
        });
        return;
    },

    //初始化websocket链接
    initWebsocket: function() {
        var _self = this
        _self.webSocket = new WebSocket(this.websocketUrl), self = this;
        _self.webSocket.onopen = function() {
            //self.webSocket.send("发送数据");
            console.log("WS连接已打开了哦～");
        };

        //每隔5秒钟发送一次心跳，避免websocket连接因超时而自动断开
        window.setInterval(function() {
            var ping = { "type": "ping" }
            _self.webSocket.send(JSON.stringify(ping));
        }, 5000);

        _self.webSocket.onmessage = function(evt) {
            console.log('收到消息：' + evt.data);
            // return;
            var received_msg = evt.data;
            received_msg = JSON.parse(received_msg)
                // _self.webSocket.send('收到了新消息')
                // console.log(received_msg);
            var content = received_msg['content'],
                msgType = received_msg['type'];
            //来新的聊天消息了
            if (msgType == 'new_msg') {
                console.log('新消息：', content);
                for (var k in content) {
                    var from_uid = content[k]['from_userid'];
                    var to_uid = content[k]['to_uid'];
                    if (undefined == self.userList[k]) {
                        console.log('对话框未有记录，需新建对话..')
                        var inValid = self.validUserIds.length > 0 &&
                            ($.inArray(from_uid, self.validUserIds) != -1 || $.inArray(to_uid, self.validUserIds) != -1);
                        //重新初始化列表
                        if (self.validUserIds.length == 0 ||
                            (inValid && content[k]['detail']['MsgType'] != 'TIMCustomElem')
                        ) {
                            console.log('刷新用户聊天对话框..')
                            self.initUserList(k);
                        }
                        return false;
                    }
                    //对方发的消息，显示红点提示
                    if (content[k]['send'] == 0) self.showNewTip(k);
                    // console.log('收到新消息：', content);
                    self.userList[k].msg_list.push(content[k])
                    if (self.curListKey == k) self.initMessageList(k);
                }
            }
            //发送消息回调
            else if (msgType == 'send_callback') {
                //alert('发送消息回调完成')
                console.log('回调消息：', content);
                self.userList[received_msg['key']].msg_list.push(content)
            }
            self.scrollDown();
        };

        _self.webSocket.onclose = function() {
            // 关闭 websocket
            console.log("WS连接已关闭～");
            //重连
            // window.setTimeout(function () {
            _self.initWebsocket()
                // }, 5000);
        };
    },

    //展示新消息提示
    showNewTip: function(k) {
        $('#' + k).find('i.new_msg').show();
    },

    //初始化消息列表
    initMessageList: function(key) {
        var msgObj = this.userList[key],
            str, msg, message, msgType;
        var chatName;
        var messages_text = $(".messages-text");
        var msgNum = msgObj.msg_list.length;
        var start = msgNum >= this.msgMaxNum ? msgNum - this.msgMaxNum : 0;
        console.log('消息数量：', msgNum, '；开始索引：', start);
        messages_text.html('');
        //for (i in msgObj.msg_list) {
        for (var i = start; i < msgNum; i++) {
            msg = msgObj.msg_list[i];
            chatName = msg.send == 1 ? msgObj.user_name : msgObj.chat_user_name;
            //图片消息
            if (msg.detail.MsgType == 'RC:ImgMsg' || msg.detail.MsgType == 'JT:USER_IMAGE') {
                msgType = this.msgImageType;
                message = msg.detail.MsgContent['ImgUrl'];
            }
            //文字消息
            else {
                msgType = this.msgTextType;
                message = emojione.toImage(msg.detail.MsgContent['Text']);
            }
            str = this.buildMessageUl(msg.send, chatName, msg.msg_time, message, msgType);
            messages_text.append(str);
        }
        this.scrollDown();
    },

    //滚动到最底部
    scrollDown: function() {
        //移动到底部
        var scrollHeight = $('#messages-text').prop("scrollHeight");
        $('#messages-text').animate({ scrollTop: scrollHeight }, 100);
    },

    //构造用户列表html
    buildUserList: function() {
        var html = "",
            user, isCouple = 0;
        $(".chatbar-contacts-uls").html('');
        for (var i in this.userList) {
            user = this.userList[i];
            $(".chatbar-contacts-uls").append(this.buildUserChatLi(user, i))
        }
        this.initBind();
        return;
    },

    /**
     * 单个用户对话信息
     * @param userInfo
     * @returns {string}
     */
    buildUserChatLi: function(userInfo, key) {
        var attr_str = '',
            user_attrs = ['chat_user_id', 'user_id', 'chat_account', 'user_account', 'user_name', 'chat_user_name', 'moment_id'];
        for (var j = 0; j < user_attrs.length; j++) {
            attr_str += (user_attrs[j] + "='" + userInfo[user_attrs[j]] + "' ");
        }
        attr_str += ('key=' + key);
        var name = emojione.toImage(userInfo.user_name.htmlXss());
        return "<li id='" + key + "'>" +
            "<i class='iconfont'>&#xe752;</i>" +
            "<i class='new_msg' style='display: none;'></i>" +
            "<p " + attr_str + ">" + userInfo.chat_user_name.htmlXss() + "&nbsp;&nbsp;（官方：" + name + "）</p>" +
            "<i class='couple' style='display: none;'></i></li>";
    },

    //点击事件绑定
    initBind: function() {
        var self = this;
        //点击按钮下拉
        $(".icon").on('click', function() {
            if ($(".chatbar").is(":visible")) {
                $(".chatbar").slideUp();
                $(".icon-box").removeClass('shadow');
            } else {
                $(".chatbar").slideDown();
                $(".icon-box").addClass('shadow');
            }
        });

        $(".chatbar-contacts-uls li").click(function() {
            $(".chatbar-contacts-uls li").removeClass('msg_active');
            $(this).addClass('msg_active');
            //红点消失
            $(this).find('i.new_msg').hide();
            var text = $(this).find('p').text(),
                pElement = $(this).find('p');
            self.curUserId = pElement.attr('user_id');
            self.curChatId = pElement.attr('chat_user_id');
            self.curUserName = pElement.attr('user_name');
            self.curChatName = pElement.attr('chat_user_name');
            self.curUserAccount = pElement.attr('user_account');
            self.curChatAccount = pElement.attr('chat_account');
            // self.curMomentId = pElement.attr('moment_id');
            self.curListKey = $(this).attr('id');
            var msgKey = pElement.attr('key');
            //alert(userId);
            $(".chatbar-messages").show().css({
                "transform": "translate3d(100%, 0, 0)"
            });
            $('.messages-title h4').html(text);
            var chat_href = self.adminUrl + 'user/list?id=' + self.curChatId;
            var user_href = self.adminUrl + 'user/official?id=' + self.curUserId;
            var user_moment_href = self.adminUrl + 'moment/all_moment?user_id=' + self.curUserId;
            var chat_moment_href = self.adminUrl + 'moment/all_moment?user_id=' + self.curChatId;
            var intro = '用户：<a href="' + chat_href + '" target="_blank">' + self.curChatId +
                '</a>；官方用户：<a href="' + user_href + '" target="_blank">' + self.curUserId +
                '</a>';
            //；<a href="' + chat_moment_href + '" target="_blank">用户动态</a>；<a href="' + user_moment_href + '" target="_blank">官方动态</a>；
            // if (parseInt(self.curMomentId) > 0) {
            //     var moment_href = self.adminUrl + 'moments?id=' + self.curMomentId;
            //     intro += '动态ID：<a href="' + moment_href + '" target="_blank">' + self.curMomentId + '</a>';
            // }
            $('.messages-title span').html(intro);
            //初始化消息
            self.initMessageList(msgKey);
        });

        //返回按钮
        $(".return-icon").click(function() {
            $(".chatbar-messages").css({
                "transform": "translate3d(0, 0, 0)"
            }).hide();
        });

        //发送消息
        $(".message-btn").on('click', function() {
            self.sendMessage();
        });

        $(document).keypress(function(e) {
            if (e.ctrlKey && e.which == 10) {
                self.sendMessage();
            }
        })

        //搜索功能
        $('.search-text').on('keyup', function() {
            var txt = $('.search-text').val();
            txt = txt.replace(/\s/g, '');
            $('.chatbar-contacts-uls li').each(function() {
                if (!$(this).is(':contains(' + txt + ')')) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
            return false;
        });
    },

    sendMessage: function() {
        var message = $('.messages-content').val();
        if (message != "undefined" && message != '') {
            this.doSendMessage(message);
        } else {
            this.messageTip('消息不能为空！');
        }
        $('.messages-content').val('')
    },

    //发送消息
    doSendMessage: function(message) {
        var timer = this.time();
        var str = this.buildMessageUl(1, this.curUserName, timer, message, 1);
        var messages_text = $(".messages-text");
        var data = {
            msg_type: 'text',
            message: message,
            from_account: this.curUserAccount,
            to_account: this.curChatAccount,
            from_userid: this.curUserId,
            to_userid: this.curChatId,
        };
        //发送消息
        this.webSocket.send(JSON.stringify(data));
        // console.log('----' + str + '===' + message);
        messages_text.append(str);
        this.scrollDown();
    },

    //发送图片消息
    sendImg: function(inputElement) {
        if (!inputElement.files || !inputElement.files[0]) {
            return;
        }
        //reader.readAsDataURL(pic.files[0]);
        var fileList = inputElement.files;
        var file = fileList[0];
        var self = this;
        //this.webSocket.send(file.name + ":fileStart");
        var reader = new FileReader();
        //以二进制形式读取文件
        reader.readAsDataURL(file); //readAsArrayBuffer
        //文件读取完毕后该函数响应
        reader.onload = function loaded(evt) {
            var data = {
                msg_type: 'image',
                message: evt.target.result,
                from_account: self.curUserAccount,
                to_account: self.curChatAccount,
            };
            //发送二进制表示的文件
            self.webSocket.send(JSON.stringify(data));
            //self.webSocket.send(file.name + ":fileFinishSingle");
            console.log('发送图片完成！');
        }
        inputElement.outerHTML = inputElement.outerHTML;
    },

    //消息提示
    messageTip: function(tip) {
        $("#message-tooltip-id").text(tip).show();
        setTimeout(function() {
            $("#message-tooltip-id").hide();
        }, 2000);
    },

    //构造消息html结构
    buildMessageUl: function(type, name, timer, message, msgType) {
        //message = '<img width=100 height=200 src="http://p.qpic.cn/opensdk_im/0/3027477162362861536_144115212593445715_807DB2D09FB561AEA764BF8F525963BE/0"></img>'
        var pClass = '';
        switch (msgType) {
            case this.msgImageType:
                message = '<img width=130 height=200 src="' + message + '"/>';
                pClass = 'msg_image';
                break;
        }
        if (type == 0) {
            ul = "<ul class='messages-text-uls " + pClass + "'><li class='messages-text-lis'>" +
                "<h4 class='messages-text-h4-other'><i></i><span>" + name + "</span><span class='time'>" +
                timer + "</span></h4>" + "<p class='messages-text-p-other " + pClass + "'>" + message + "</p>" +
                "</ul></li>";
        } else {
            ul = "<ul class='messages-text-uls " + pClass + "'><li class='messages-text-lis'>" +
                "<h4 class='messages-text-h4-my'><i></i><span>" + name + "</span><span class='time'>" +
                timer + "</span></h4>" + "<p class='messages-text-p-my " + pClass + "'>" + message + "</p>" +
                "</ul></li>";
        }
        return ul;
    },

    //时间封装
    time: function(type) {
        type = type || 'hh:mm'
        var timer = new Date();
        var year = timer.getFullYear();
        var month = timer.getMonth() + 1;
        var date = timer.getDate();
        var hour = timer.getHours();
        var min = timer.getMinutes();
        if (type == 'hh:mm') {
            hour = hour < 10 ? ('0' + hour) : hour;
            min = min < 10 ? ('0' + min) : min;
        }
        var time = year + "-" + month + "-" + date + "  " + hour + ":" + min;
        return time;
    },

    //请求数据
    postReq: function(url, data, func) {
        $.ajax({
            url: url,
            type: "POST",
            data: data,
            dataType: "json",
            success: function(response) {
                func(response)
            }
        });
    }
};

JitianIm.init();